package com.kaifamiao.tracking.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/cookie/produce/*")
public class CookieProduceServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1、创建Cookie实例
        Cookie cookie = new Cookie( "kfmid", "kaifamiao" );

        // 2、设置Cookie实例
        // cookie.setDomain( "localhost" ); // 设置cookie的域(Domain)
        cookie.setPath( "/" ); // 设置cookie的路径(Path)
        cookie.setSecure( false ); // 设置cookie的安全策略(true表示仅限https连接才能发送)
        cookie.setHttpOnly( false ); // 设置cookie是否可以在客户端通过JavaScript脚本来访问
        int expiry = 60 * 60 * 24 * 365;
        cookie.setMaxAge( expiry ); // 设置cookie最大有效期(时间以秒为单位)

        // 3、将cookie添加到响应头
        // 本质上是追加到响应头中`set-cookie`字段中
        response.addCookie( cookie );

        Cookie ck = new Cookie( "KFM_NAME", URLEncoder.encode("i am kaifamiao.", StandardCharsets.UTF_8));
        cookie.setPath( "/" );
        response.addCookie( ck );

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();

        out.println( "<h3 style='text-align: center'>");
        out.println( "请用浏览器提供的支持或用插件查看本地cookie" );
        out.println( "</h3>");

        out.println( "<script>");
        out.println( "console.log( document.cookie )");
        out.println( "</script>");
    }

}
